<template>
  <view class="container">
    <!-- 全屏图片 -->
    <image
      class="share-image"
      :src="shareImageUrl"
      mode="aspectFit"
      @error="handleImageError"
      @longpress="handleLongPress"
    ></image>
    
    <!-- 返回按钮 -->
    <view class="back-button-wrapper">
      <view class="global-header-left" @click="goBack">
        <view class="global-back-button">
          <text class="global-back-icon">‹</text>
        </view>
        <text class="global-back-text">返回</text>
      </view>
    </view>
    
    <!-- 保存提示 -->
    <view class="save-tip" @longpress="handleLongPress">
      <view class="save-tip-icon">📥</view>
      <view class="save-tip-text">
        <text class="save-tip-line1">长按保存并分‍享，</text>
        <text class="save-tip-line2">解锁每日1次抽奖</text>
      </view>
      <view class="save-tip-dot"></view>
    </view>
    
    <!-- 保存成功弹窗 -->
    <view v-if="showSuccessModal" class="success-modal-mask" @click="closeSuccessModal">
      <view class="success-modal-content" @click.stop>
        <!-- 关闭按钮 -->
        <view class="close-button" @click="closeSuccessModal">
          <image
            class="close-icon"
            src="/static/资源 1-8.png"
            mode="aspectFit"
          ></image>
        </view>
        <!-- 背景图片容器 -->
        <view class="success-modal-bg-wrapper">
          <image
            class="success-modal-bg"
            src="/static/box.png"
            mode="aspectFit"
            :style="{ width: '600rpx', height: '800rpx' }"
          ></image>
          <!-- 吉祥物图片 -->
          <image
            class="success-modal-mascot"
            :src="getModalMascotImage(shareModalButton)"
            mode="aspectFit"
          ></image>
          <!-- 提示文字 -->
          <view
            class="success-text small"
            :style="{ color: getModalTextColor(shareModalButton) }"
          >
            <template v-if="shareModalText && shareModalText.includes('\n')">
              <text
                v-for="(line, index) in shareModalText.split('\n')"
                :key="index"
              >{{ line }}</text>
            </template>
            <text v-else>{{ shareModalText }}</text>
          </view>
          <!-- 按钮 -->
          <view class="lottery-button" @click="handleModalButton" v-if="shareModalButton">
            {{ shareModalButton }}
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getImageUrl } from '@/api/config'
import { addLotteryChance } from '@/api/lottery'
import { SpbLottryType } from '@/api/apifox/models'

export default {
  data() {
    return {
      theme: '', // 主题：温暖同行、活力四射、自由随性、勇往直前
      gender: '男', // 性别：男、女，默认男性
      shareImageUrl: '', // 分享图片URL
      isSaving: false, // 是否正在保存
      showSuccessModal: false, // 是否显示成功弹窗
      shareModalText: '', // 弹窗文案
      shareModalButton: '' // 弹窗按钮文字
    };
  },
  onLoad(options) {
    // 接收从 playlist-detail 页面传递的参数
    if (options.theme) {
      this.theme = decodeURIComponent(options.theme);
    }
    if (options.gender) {
      this.gender = decodeURIComponent(options.gender);
    }
    
    // 生成分享图片URL
    this.generateShareImageUrl();
  },
  methods: {
    getImageUrl,
    goBack() {
      uni.reLaunch({
        url: '/pages/index/index'
      });
    },
    /**
     * 获取今日日期字符串（格式：YYYY-MM-DD）
     */
    getTodayDateString() {
      const today = new Date()
      const year = today.getFullYear()
      const month = String(today.getMonth() + 1).padStart(2, '0')
      const day = String(today.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    /**
     * 获取分享缓存键名
     */
    getShareCacheKey() {
      const today = this.getTodayDateString()
      return `song_share_${today}`
    },
    /**
     * 检查当日分享缓存
     */
    checkTodayShare() {
      const cacheKey = this.getShareCacheKey()
      const cached = uni.getStorageSync(cacheKey)
      
      if (cached) {
        // 有缓存，显示"今日抽奖已完成"
        this.shareModalText = '今日抽奖已完成'
        this.shareModalButton = '知道了'
        this.showSuccessModal = true
      } else {
        // 没有缓存，设置缓存并显示提示
        uni.setStorageSync(cacheKey, true)
        this.shareModalText = '恭喜获得\n1次抽奖机会'
        this.shareModalButton = '立即抽奖'
        this.showSuccessModal = true
        // 调用增加抽奖机会接口
        this.addLotteryChanceForSongShare()
      }
    },
    // 获取关键词对应的拼音首字母（前四个字）
    getKeywordInitials(keyword) {
      // 关键词到拼音首字母的映射
      const keywordMap = {
        '温暖同行': 'WNTX', // Wen Nuan Tong Xing
        '活力四射': 'HLSS', // Huo Li Si She
        '自由随性': 'ZYSX', // Zi You Sui Xing
        '勇往直前': 'YWZQ', // Yong Wang Zhi Qian
      };
      return keywordMap[keyword] || 'WNTX'; // 默认值
    },
    /**
     * 根据主题和性别生成分享图片URL
     */
    generateShareImageUrl() {
      if (!this.theme) {
        // 如果没有主题，返回默认图片
        this.shareImageUrl = this.getImageUrl('poster2/YWZQMS.jpg');
        return;
      }
      
      // 获取关键词的拼音首字母（前四个字母）
      const initials = this.getKeywordInitials(this.theme);
      
      // 根据性别获取后缀：M-男，F-女
      const genderSuffix = this.gender === '女' ? 'F' : 'M';
      
      // 组合文件名：前四个字母 + 性别后缀 + S + .jpg
      const fileName = `${initials}${genderSuffix}S.jpg`;
      
      // 返回完整的URL
      this.shareImageUrl = `https://hykoc.oss-cn-beijing.aliyuncs.com/koc/tc2025/poster2/${fileName}`;
    },
    /**
     * 图片加载错误处理
     */
    handleImageError(e) {
      console.error('分享图片加载失败:', e);
      uni.showToast({
        title: '图片加载失败',
        icon: 'none',
        duration: 2000,
      });
    },
    /**
     * 长按图片保存到相册
     */
    async handleLongPress() {
      if (this.isSaving) {
        return;
      }
      
      if (!this.shareImageUrl) {
        uni.showToast({
          title: '图片未加载完成',
          icon: 'none',
          duration: 2000,
        });
        return;
      }
      
      this.isSaving = true;
      
      try {
        // 先下载图片到本地
        uni.showLoading({
          title: '保存中...',
          mask: true,
        });
        
        const downloadResult = await new Promise((resolve, reject) => {
          uni.downloadFile({
            url: this.shareImageUrl,
            success: resolve,
            fail: reject,
          });
        });
        
        if (downloadResult.statusCode !== 200) {
          throw { errMsg: 'download failed', message: '图片下载失败' };
        }
        
        // 保存图片到相册
        await new Promise((resolve, reject) => {
          uni.saveImageToPhotosAlbum({
            filePath: downloadResult.tempFilePath,
            success: resolve,
            fail: reject,
          });
        });
        
        uni.hideLoading();
        // 检查当日分享缓存并显示弹窗
        this.checkTodayShare();
      } catch (error) {
        console.error('保存图片失败:', error);
        uni.hideLoading();
        
        // 检查是否是权限被拒绝的情况
        const isPermissionDenied = error.errMsg && (
          error.errMsg.includes('auth deny') || 
          error.errMsg.includes('authorize') ||
          error.errMsg.includes('permission') ||
          error.errMsg.includes('权限')
        );
        
        if (isPermissionDenied) {
          // 权限被拒绝，显示引导对话框
          this.showPermissionGuide();
        } else {
          // 其他错误，显示普通提示
          let errorMessage = '保存失败，请重试';
          // 检查错误信息（同时支持 errMsg 和 message）
          const errorText = error.errMsg || error.message || '';
          if (errorText.includes('download') || errorText.includes('下载失败')) {
            errorMessage = '图片下载失败';
          } else if (errorText.includes('save') || errorText.includes('保存失败')) {
            errorMessage = '保存失败';
          }
          
          uni.showToast({
            title: errorMessage,
            icon: 'none',
            duration: 2000,
          });
        }
      } finally {
        this.isSaving = false;
      }
    },
    /**
     * 显示权限引导对话框
     */
    showPermissionGuide() {
      uni.showModal({
        title: '需要相册权限',
        content: '保存图片需要访问您的相册权限，请在设置中开启相册权限后重试',
        confirmText: '去设置',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            // 用户点击"去设置"，打开设置页面
            this.openSettings();
          }
        },
      });
    },
    /**
     * 打开设置页面
     */
    openSettings() {
      uni.openSetting({
        success: (settingRes) => {
          console.log('设置页面返回结果:', settingRes.authSetting);
          // 检查用户是否在设置中开启了相册权限
          // 微信小程序使用 scope.writePhotosAlbum
          const photoPermission = settingRes.authSetting['scope.writePhotosAlbum'];
          
          if (photoPermission === true) {
            // 用户在设置中开启了权限
            uni.showToast({
              title: '权限已开启，请重新长按保存',
              icon: 'success',
              duration: 2000,
            });
          } else if (photoPermission === false) {
            // 用户仍然没有开启权限
            uni.showToast({
              title: '请在设置中开启相册权限',
              icon: 'none',
              duration: 2000,
            });
          } else {
            // 权限状态未知，提示用户重试
            uni.showToast({
              title: '请确保已开启相册权限',
              icon: 'none',
              duration: 2000,
            });
          }
        },
        fail: (err) => {
          console.error('打开设置失败:', err);
          uni.showToast({
            title: '无法打开设置，请手动前往系统设置',
            icon: 'none',
            duration: 3000,
          });
        },
      });
    },
    /**
     * 关闭成功弹窗
     */
    closeSuccessModal() {
      this.showSuccessModal = false;
    },
    /**
     * 处理弹窗按钮点击
     */
    handleModalButton() {
      // 如果是首次分享（恭喜获得抽奖机会），点击"立即抽奖"后跳转到抽奖页面
      if (this.shareModalText.includes('恭喜获得')) {
        this.closeSuccessModal();
        uni.navigateTo({
          url: '/pages/lottery/index'
        });
      } else {
        // 其他情况（今日抽奖已完成）直接关闭
        this.closeSuccessModal();
      }
    },
    /**
     * 获取弹窗吉祥物图片（通用函数）
     * @param {string} buttonText - 按钮文本
     * @returns {string} 返回图片路径
     */
    getModalMascotImage(buttonText) {
      // 当按钮是"立即捐步"时，使用资源 4.png，否则使用资源 33-8.png
      if (buttonText === "立即捐步") {
        return "/static/资源 4.png";
      }
      return "/static/资源 33-8.png";
    },
    /**
     * 获取弹窗文字颜色（通用函数）
     * @param {string} buttonText - 按钮文本
     * @returns {string} 返回颜色值
     */
    getModalTextColor(buttonText) {
      // 当按钮是"立即捐步"时，使用蓝色，否则使用红色
      if (buttonText === "立即捐步") {
        return "#1b6ec1";
      }
      return "#f03c32";
    },
    /**
     * 为歌单分享增加抽奖机会
     */
    async addLotteryChanceForSongShare() {
      try {
        await addLotteryChance({
          lottryType: SpbLottryType.LottryTypeSongShare
        });
        console.log('增加抽奖机会成功');
      } catch (error) {
        console.error('增加抽奖机会失败:', error);
        // 静默失败，不影响用户体验
      }
    },
  },
};
</script>

<style scoped>
.container {
  width: 100%;
  height: 100vh;
  position: relative;
  overflow: hidden;
  background-color: #000000; /* 黑色背景 */
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 全屏图片 */
.share-image {
  width: 100%;
  height: 100%;
  object-fit: contain; /* 保持比例，完整显示图片 */
}

/* 返回按钮包装器 */
.back-button-wrapper {
  position: absolute;
  top: calc(var(--status-bar-height, 44rpx) + 60rpx);
  left: 30rpx;
  z-index: 100;
}

/* 全局返回按钮样式 */
.global-back-button {
  width: 60rpx;
  height: 60rpx;
  background: #ff0000;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15rpx;
}

.global-back-icon {
  color: white;
  font-size: 40rpx;
  font-weight: bold;
  line-height: 1;
}

.global-back-text {
  color: white;
  font-size: 28rpx;
  font-weight: bold;
}

.global-header-left {
  display: flex;
  align-items: center;
}

/* 保存提示 */
.save-tip {
  position: absolute;
  bottom: 120rpx;
  left: 50%;
  transform: translateX(-50%);
  z-index: 100;
  background: linear-gradient(135deg, rgba(255, 77, 77, 0.95) 0%, rgba(255, 140, 0, 0.95) 100%);
  padding: 20rpx 40rpx;
  border-radius: 50rpx;
  backdrop-filter: blur(10rpx);
  box-shadow: 0 8rpx 24rpx rgba(255, 77, 77, 0.4), 
              0 0 0 2rpx rgba(255, 255, 255, 0.3);
  display: flex;
  align-items: center;
  gap: 12rpx;
  animation: floatUpDown 2s ease-in-out infinite, 
             pulse 2s ease-in-out infinite;
}

.save-tip-icon {
  font-size: 32rpx;
  color: #ffffff;
  animation: bounce 1.5s ease-in-out infinite;
  font-weight: bold;
}

.save-tip-text {
  color: #ffffff;
  font-size: 30rpx;
  font-weight: 600;
  text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.3);
  letter-spacing: 2rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  line-height: 1.4;
}

.save-tip-text text {
  color: inherit;
  font-size: inherit;
  font-weight: inherit;
  text-shadow: inherit;
  letter-spacing: inherit;
}

.save-tip-line1 {
  white-space: nowrap;
}

.save-tip-line2 {
  white-space: nowrap;
}

.save-tip-dot {
  width: 8rpx;
  height: 8rpx;
  background: #ffffff;
  border-radius: 50%;
  animation: blink 1.5s ease-in-out infinite;
  box-shadow: 0 0 8rpx rgba(255, 255, 255, 0.8);
}

/* 上下浮动动画 */
@keyframes floatUpDown {
  0%, 100% {
    transform: translateX(-50%) translateY(0);
  }
  50% {
    transform: translateX(-50%) translateY(-10rpx);
  }
}

/* 脉冲动画 */
@keyframes pulse {
  0%, 100% {
    box-shadow: 0 8rpx 24rpx rgba(255, 77, 77, 0.4), 
                0 0 0 2rpx rgba(255, 255, 255, 0.3);
  }
  50% {
    box-shadow: 0 12rpx 32rpx rgba(255, 77, 77, 0.6), 
                0 0 0 4rpx rgba(255, 255, 255, 0.5);
  }
}

/* 图标弹跳动画 */
@keyframes bounce {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-6rpx);
  }
}

/* 闪烁动画 */
@keyframes blink {
  0%, 100% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.3;
    transform: scale(0.8);
  }
}

/* 响应式调整 */
@media screen and (max-width: 750rpx) {
  .back-button-wrapper {
    top: calc(var(--status-bar-height, 44rpx) + 40rpx);
    left: 20rpx;
  }
  
  .save-tip {
    bottom: 80rpx;
    padding: 16rpx 32rpx;
    gap: 10rpx;
  }
  
  .save-tip-icon {
    font-size: 28rpx;
  }
  
  .save-tip-text {
    font-size: 26rpx;
  }
  
  .save-tip-dot {
    width: 6rpx;
    height: 6rpx;
  }
}

/* 成功弹窗遮罩层 */
.success-modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.3s ease-in-out;
}

/* 成功弹窗内容 */
.success-modal-content {
  position: relative;
  width: 600rpx;
  max-width: 90%;
  display: flex;
  flex-direction: column;
  align-items: center;
  animation: scaleIn 0.3s ease-in-out;
}

/* 背景图片容器 */
.success-modal-bg-wrapper {
  position: relative;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-bottom: 150rpx;
}

/* 关闭按钮 */
.close-button {
  position: absolute;
  top: 20rpx;
  right: -20rpx;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1001;
  cursor: pointer;
}

/* 关闭图标 */
.close-icon {
  width: 60rpx;
  height: 60rpx;
}

/* 背景图片 */
.success-modal-bg {
  width: 600rpx;
  height: 800rpx;
  border-radius: 20rpx;
}

/* 吉祥物图片 */
.success-modal-mascot {
  position: absolute;
  top: 32%;
  left: 50%;
  transform: translateX(-50%);
  width: 200rpx;
  height: 200rpx;
  z-index: 10;
}

/* 提示文字 */
.success-text {
  position: absolute;
  top: 65%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #ff0000;
  font-size: 66rpx;
  font-weight: bold;
  text-align: center;
  z-index: 10;
  text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.success-text.small {
  font-size: 42rpx;
}

.success-text text {
  display: block;
  line-height: 1.5;
}

/* 立即抽奖按钮 */
.lottery-button {
  position: absolute;
  bottom: 40rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 400rpx;
  height: 88rpx;
  background: #ff0000;
  border-radius: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ffffff;
  font-size: 36rpx;
  font-weight: bold;
  box-shadow: 0 8rpx 24rpx rgba(255, 0, 0, 0.4);
  transition: all 0.3s ease;
  z-index: 10;
}

.lottery-button:active {
  transform: translateX(-50%) scale(0.95);
  box-shadow: 0 4rpx 12rpx rgba(255, 0, 0, 0.3);
}

/* 弹窗淡入动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

/* 弹窗缩放动画 */
@keyframes scaleIn {
  from {
    transform: scale(0.8);
    opacity: 0;
  }
  to {
    transform: scale(1);
    opacity: 1;
  }
}
</style>

